package com.liuchen.common.util;

import com.liuchen.boot.system.BaseApplication;
import org.apache.log4j.PropertyConfigurator;
import java.util.*;

/**
 * Created by liuchen on 2017/3/28.
 * spring-boot中使用
 * 能处理环境的配置文件读取工具
 */
public class PropertiesEnvUtils {

    /**
     * 加载当前环境下的log4j配置文件
     */
    public static void loadLog4jPro() {
        PropertyConfigurator.configure("config/" + BaseApplication.env + "/log4j");
    }

    /**
     * 获取其中一个值
     *
     * @param path
     * @param key
     * @return
     */
    public static String getPropertiesString(String path, String key) {
        ResourceBundle rb;
        if (path == null) {
            rb = ResourceBundle.getBundle("application-" + BaseApplication.env);
        } else {
            rb = ResourceBundle.getBundle("config/" + BaseApplication.env + "/" + path);
        }
        String re;
        try{
            re = rb.getString(key);
        }catch(Exception e){
            rb = ResourceBundle.getBundle("application");
            re = rb.getString(key);
        }
        re = randomInt(re);
        return re;
    }

    /**
     * 获取整个ResourceBundle对象返回一个map
     *
     * @param path
     * @return
     */
    public static Map<String, String> getPropertiesMap(String path) {
        ResourceBundle rb;
        if (path == null) {
            rb = ResourceBundle.getBundle("application-" + BaseApplication.env);
        } else {
            rb = ResourceBundle.getBundle("config/" + BaseApplication.env + "/" + path);
        }
        Set<String> keys = rb.keySet();
        Map<String, String> reMap = new HashMap<>();
        for (String str : keys) {
            String re = rb.getString(str);
            re = randomInt(re);
            reMap.put(str, re);
        }
        return reMap;
    }

    /**
     * 判断生成随机数
     *
     * @param re
     * @return
     */
    private static String randomInt(String re) {
        re = re.replaceAll(" ", "");
        if (re.contains("${random.int")) {
            re = re.substring(13, re.length() - 2);
            if (re.contains(",")) {
                String[] num = re.split(",");
                int min = Integer.parseInt(num[0]);
                int max = Integer.parseInt(num[1]);
                Random rand = new Random();
                re = Integer.toString(rand.nextInt(max - min) + min);
            } else {
                int max = Integer.parseInt(re);
                Random rand = new Random();
                re = Integer.toString(rand.nextInt(max));
            }
        }
        return re;
    }


}
